<?php
/**
 * api签名验证中间件
 * User: zucheng
 * Date: 2019/03/18
 */

namespace App\Http\Middleware;

use Closure;
use App\Library\Common;
use App\Library\R;

class ApiMiddleware
{
    /**
     * Handle an incoming request.
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $params = $request->input();
        // 签名验证开关
        $openCheck = config('api.open_check');
        if (!$openCheck) {
            return $next($request);
        }

        // 授权验证
        $app = config('api.app');
        if (!isset($params['app_key']) || !isset($app[$params['app_key']])) {
            return R::error("未知授权");
        }

        if (!isset($params['sign'])) {
            return R::error("缺少签名");
        }

        // 签名验证
        $createSign = Common::createSign($params, $app[$params['app_key']]);
        if ($params['sign'] !== $createSign) {
            return R::error("签名验证失败");
        }

        return $next($request);
    }
}
